/**
 * 认证路由
 * Authentication Routes
 */

const express = require('express');
const { body, validationResult } = require('express-validator');
const rateLimit = require('express-rate-limit');
const router = express.Router();

const User = require('../database/models/User');
const { createSession, destroySession, authMiddleware } = require('../middleware/auth');
const authService = require('../services/AuthService');
const sessionService = require('../services/SessionService');
const logger = require('../utils/logger');

// 登录频率限制 - 更严格的限制
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 5, // 每15分钟最多5次登录尝试
  message: {
    success: false,
    message: '登录尝试过于频繁，请15分钟后再试 / Too many login attempts, please try again in 15 minutes'
  },
  standardHeaders: true,
  legacyHeaders: false,
  // 根据IP和邮箱组合限制
  keyGenerator: (req) => {
    return `${req.ip}-${req.body.email || 'unknown'}`;
  }
});

/**
 * 用户登录
 * POST /api/auth/login
 */
router.post('/login', 
  loginLimiter,
  [
    body('email')
      .isEmail()
      .normalizeEmail()
      .withMessage('请输入有效的邮箱地址 / Please enter a valid email address'),
    body('password')
      .isLength({ min: 6 })
      .withMessage('密码至少6位字符 / Password must be at least 6 characters')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { email, password, rememberMe = false } = req.body;
      const clientIP = req.ip || req.connection.remoteAddress;

      logger.info('用户登录尝试 / User login attempt', {
        email,
        ip: clientIP,
        userAgent: req.get('User-Agent')
      });

      // 使用认证服务进行登录
      const user = await authService.login(email, password, clientIP, req.get('User-Agent'));

      // 创建会话
      const sessionData = createSession(user, {
        clientIP,
        userAgent: req.get('User-Agent'),
        rememberMe
      });

      logger.info('用户登录成功 / User login successful', {
        userId: user.id,
        email: user.email,
        ip: clientIP,
        sessionId: sessionData.sessionId
      });

      // 返回登录成功响应
      res.json({
        success: true,
        message: '登录成功 / Login successful',
        token: sessionData.token,
        user: {
          id: user.id,
          email: user.email,
          nickname: user.nickname,
          role: user.role,
          avatar: user.avatar,
          storage_used: user.storage_used,
          storage_limit: user.storage_limit
        },
        expiresAt: sessionData.expiresAt
      });

    } catch (error) {
      logger.error('登录处理失败 / Login processing failed', {
        email: req.body.email,
        error: error.message,
        stack: error.stack
      });
      next(error);
    }
  }
);

/**
 * 用户登出
 * POST /api/auth/logout
 */
router.post('/logout', authMiddleware, async (req, res, next) => {
  try {
    const { sessionId, id: userId, email } = req.user;

    // 销毁会话
    const destroyed = destroySession(sessionId);

    if (destroyed) {
      logger.info('用户登出成功 / User logout successful', {
        userId,
        email,
        sessionId
      });
    }

    res.json({
      success: true,
      message: '登出成功 / Logout successful'
    });

  } catch (error) {
    logger.error('登出处理失败 / Logout processing failed', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 验证令牌
 * GET /api/auth/verify
 */
router.get('/verify', authMiddleware, async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    // 获取最新的用户信息
    const user = await User.findById(userId, 'id, email, nickname, role, avatar, storage_used, storage_limit, is_active');
    
    if (!user || !user.is_active) {
      return res.status(401).json({
        success: false,
        message: '用户账户不存在或已被禁用 / User account not found or disabled'
      });
    }

    res.json({
      success: true,
      message: '令牌验证成功 / Token verification successful',
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        role: user.role,
        avatar: user.avatar,
        storage_used: user.storage_used,
        storage_limit: user.storage_limit
      }
    });

  } catch (error) {
    logger.error('令牌验证失败 / Token verification failed', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 获取登录状态
 * GET /api/auth/status
 */
router.get('/status', (req, res) => {
  // 这个端点不需要认证，用于检查服务器状态
  res.json({
    success: true,
    message: '认证服务正常 / Authentication service is running',
    timestamp: new Date().toISOString()
  });
});

/**
 * 刷新令牌（可选功能）
 * POST /api/auth/refresh
 */
router.post('/refresh', authMiddleware, async (req, res, next) => {
  try {
    const { id: userId, sessionId } = req.user;

    // 获取用户信息
    const user = await User.findById(userId);
    if (!user || !user.is_active) {
      return res.status(401).json({
        success: false,
        message: '用户账户不存在或已被禁用 / User account not found or disabled'
      });
    }

    // 销毁旧会话
    destroySession(sessionId);

    // 创建新会话
    const newSessionData = createSession(user, {
      clientIP: req.ip,
      userAgent: req.get('User-Agent')
    });

    logger.info('令牌刷新成功 / Token refresh successful', {
      userId,
      oldSessionId: sessionId.substring(0, 8) + '...',
      newSessionId: newSessionData.sessionId.substring(0, 8) + '...'
    });

    res.json({
      success: true,
      message: '令牌刷新成功 / Token refresh successful',
      token: newSessionData.token,
      expiresAt: newSessionData.expiresAt
    });

  } catch (error) {
    logger.error('令牌刷新失败 / Token refresh failed', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 获取用户的活跃会话列表
 * GET /api/auth/sessions
 */
router.get('/sessions', authMiddleware, async (req, res, next) => {
  try {
    const { id: userId, sessionId: currentSessionId } = req.user;

    const sessions = sessionService.getUserSessions(userId);
    
    // 标记当前会话
    sessions.forEach(session => {
      if (session.sessionId.startsWith(currentSessionId.substring(0, 8))) {
        session.current = true;
      }
    });

    res.json({
      success: true,
      message: '获取会话列表成功 / Get sessions list successful',
      sessions
    });

  } catch (error) {
    logger.error('获取会话列表失败 / Failed to get sessions list', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 销毁指定会话
 * DELETE /api/auth/sessions/:sessionId
 */
router.delete('/sessions/:sessionId', authMiddleware, async (req, res, next) => {
  try {
    const { id: userId } = req.user;
    const { sessionId } = req.params;

    // 验证会话所有权
    const userSessions = sessionService.getUserSessions(userId);
    const targetSession = userSessions.find(s => s.sessionId.startsWith(sessionId.substring(0, 8)));

    if (!targetSession) {
      return res.status(404).json({
        success: false,
        message: '会话不存在 / Session not found'
      });
    }

    // 销毁会话
    const destroyed = sessionService.destroySession(sessionId);

    if (destroyed) {
      logger.info('会话销毁成功 / Session destroyed successfully', {
        userId,
        sessionId: sessionId.substring(0, 8) + '...'
      });

      res.json({
        success: true,
        message: '会话销毁成功 / Session destroyed successfully'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '会话不存在 / Session not found'
      });
    }

  } catch (error) {
    logger.error('销毁会话失败 / Failed to destroy session', {
      userId: req.user?.id,
      sessionId: req.params.sessionId,
      error: error.message
    });
    next(error);
  }
});

/**
 * 销毁所有其他会话（保留当前会话）
 * POST /api/auth/sessions/destroy-others
 */
router.post('/sessions/destroy-others', authMiddleware, async (req, res, next) => {
  try {
    const { id: userId, sessionId: currentSessionId } = req.user;

    // 获取用户所有会话
    const userSessions = sessionService.getUserSessions(userId);
    let destroyedCount = 0;

    // 销毁除当前会话外的所有会话
    for (const session of userSessions) {
      const fullSessionId = session.sessionId.replace('...', ''); // 这里需要完整的sessionId
      if (fullSessionId !== currentSessionId) {
        if (sessionService.destroySession(fullSessionId)) {
          destroyedCount++;
        }
      }
    }

    logger.info('其他会话已销毁 / Other sessions destroyed', {
      userId,
      destroyedCount,
      currentSessionId: currentSessionId.substring(0, 8) + '...'
    });

    res.json({
      success: true,
      message: `成功销毁${destroyedCount}个其他会话 / Successfully destroyed ${destroyedCount} other sessions`,
      destroyedCount
    });

  } catch (error) {
    logger.error('销毁其他会话失败 / Failed to destroy other sessions', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

module.exports = router;